MusisUsers = new Mongo.Collection('musicusers');
Recommendations = new Mongo.Collection('recommendations');
Favorites = new Mongo.Collection('favorites');

if (Meteor.isClient) {
  // counter starts at 0
  Session.setDefault('counter', 0);

  Template.hello.helpers({
    counter: function () {
      return Session.get('counter');
    }
  });

  Template.hello.events({
    'click button': function () {
      // increment the counter when button is clicked
      Session.set('counter', Session.get('counter') + 1);
    }
  });
}

if (Meteor.isServer) {
  Meteor.startup(function () {

    Restivus.addCollection(Meteor.users);

      // Global API configuration
    Restivus.configure({
      useAuth: false,
      prettyJson: true,
      enableCors: true,
      defaultHeaders: {
        'Content-Type': 'application/json',
        'Access-Control-Allow-Origin': '*'
      }
    });

    Restivus.addRoute('login', {authRequired: false}, {
      post : {
        action: function () {
          var user = Meteor.users.findOne( {'username': this.queryParams.username} );
          console.log('login action');
          if (user) {
            return {username: user.username, session_id: user._id, favorites: user.favorites};
          }
          return {
            headers: {
              'Content-Type': 'text/json',
              'X-Custom-Header': 'custom value',
              'Access-Control-Allow-Origin': '*'
            },            
            statusCode: 400,
            body: {status: "fail", message: "Not found this user, Unable to login"}
          };
        }
      },
    });
    Restivus.addRoute('signup', {authRequired: false}, {
      post : {
        action: function () {
          console.log('signup action');
          var user = Meteor.users.findOne( {'username': this.queryParams.username} );
          if (user) {
            return {
              statusCode: 400,
              body: {status: "fail", message: "Unable to signup, already signup"}
            };
            //return {status: "success", data: user};
          }

          var userData  = {username: this.queryParams.username, favorites: []};
          var uid = Meteor.users.insert(userData);
          userData.session_id = uid;
          return userData;
        }
      },
    });
    Restivus.addRoute('postrec', {authRequired: false}, {
      post : {
        action: function () {
          //console.log(this.bodyParams);
          return Recommendations.insert(this.bodyParams);
        }
      },
    });    
    
    Restivus.addRoute('recommendations', {authRequired: false}, {
      get : {
        action: function () {
          //console.log('recommendations action');
          var count = Recommendations.find({}).count();
          var skip = Math.random() * count;
          var rec = Recommendations.find({}, {
            skip: skip,
            limit: 10,
          }).fetch();
          if (rec) {
            return rec;
          }
          return {
            statusCode: 400,
            body: {status: "fail", message: "Unable to find recommendations"}
          };
        }
      },
    });


    Restivus.addRoute('favorites', {authRequired: false}, {
      post : {
        action: function () {
          if (this.queryParams.method == 'add') {
            var fav = Recommendations.findOne({ song_id: this.queryParams.song_id });

            Meteor.users.update(this.queryParams.session_id, { $push: { favorites: fav } });
            return {status: "success", data: this.queryParams.song_id};
          } else if (this.queryParams.method == 'delete') {
            Meteor.users.update({_id: this.queryParams.session_id}, {$pull: { favorites: {song_id: this.queryParams.song_id} }}
            /*  , { multi: true }*/
            );
            return {status: "success"};
          }
/*
          return {
            statusCode: 400,
            body: {status: "fail", message: "Unable to add favorites"}
          };*/
        }
      },
      get : {
        action: function () {
          var user = Meteor.users.findOne( this.queryParams.session_id );
          if (user) {
            //user.favorites.push(this.queryParams.song_id);
            return user.favorites;
          }

          return {
            statusCode: 400,
            body: {status: "fail", message: "Unable to get favorites"}
          };
        }
      },  
    });

    // code to run on server at startup
  });
}


/*
artist: "Mariah Carey"image_large: "https://i.scdn.co/image/021fe86098015008463597fbd1b40ea0aca3bb14"image_medium: "https://i.scdn.co/image/78d2d152c50e139dd29bd8e02f892bfc3af7fc6b"image_small: "https://i.scdn.co/image/49ddb3c72d514b9764cd0e90eee2fe218cb9ae3b"loaded: trueopen_url: "https://open.spotify.com/track/6bI6M5us38PGt2QfVlEWvL"preview_url: "https://p.scdn.co/mp3-preview/00decb63e6cabdfd26d939fd55b84e27ab21e652"song_id: "54dd0bc8a57fa90c00770547"title: "We Belong Together"
 */